package net.xdclass.controller;

import net.xdclass.domain.Video;
import net.xdclass.domain.VideoOrder;
import net.xdclass.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/order")
public class OrderController {

    @Autowired
    private VideoService videoService;

    /*@Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;*/

    @RequestMapping("/find_by_id")
    public Object findById(int videoId) {
        /*Video video = restTemplate
                .getForObject("http://localhost:9000/api/v1/video/find_by_id?videoId=" + videoId, Video.class);*/

        /*List<ServiceInstance> instances = discoveryClient.getInstances("xdclass-video-service");
        ServiceInstance serviceInstance = instances.get(0);
        Video video = restTemplate
                .getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/api/v1/video/find_by_id?videoId=" + videoId, Video.class);*/
        /*Video video = restTemplate
                .getForObject("http://xdclass-video-service/api/v1/video/find_by_id?videoId=" + videoId, Video.class);*/
        Video video = videoService.findById(videoId);
        VideoOrder videoOrder = new VideoOrder();
        videoOrder.setVideoId(videoId);
        videoOrder.setVideoTitle(video.getTitle());
        videoOrder.setVideoImg(video.getCoverImg());
        videoOrder.setCreateTime(new Date());
        videoOrder.setVideoInfo(video.getVideoInfo());
        return videoOrder;
    }

    @PostMapping("/save")
    public Object save(@RequestBody Video video) {
        Integer rows = videoService.save(video);
        Map<String, Object> map = new HashMap<>();
        map.put("rows", rows);
        return map;
    }


    @RequestMapping("/list")
    public Object list() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>();
        map.put("title1", "标题1");
        map.put("title2", "标题2");
        return map;
    }
}
